#pragma once

#include <iostream>
#include <string>
#include <strings.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define defaultip "0.0.0.0"
#define defaulport 8080
class Server
{
public:
    enum{SOCKETFD_ERRNO = 1,SOCKETBIND_ERRNO = 2};

    Server(const uint16_t port = defaulport, const std::string& ip = defaultip):_port(port), _ip(ip)
    {}

    void initServer()
    {
          //创建网络udp文件
          int socketfd = socket(AF_INET,SOCK_STREAM,0);
          
          if(socketfd == - 1)
          {
              std::cout << errno << strerror(errno) << std::endl;
              exit(1);
          }
          _socketfd = socketfd;
          // 开始正式建立连接
          struct sockaddr_in address;
          bzero(&address,sizeof(address));
          address.sin_family = AF_INET;
          //转为网络大端数据
          address.sin_port = htons(_port);
          //inet_addr可以把 string -> char* -> 网络数据，可谓是一步到位
          address.sin_addr.s_addr = inet_addr(_ip.c_str());
          //填充这个结构图异常重要
          int ret = bind(socketfd,(struct sockaddr*)&address,sizeof address);
          if(ret == -1)
          {
            std::cout << errno << strerror(errno) << std::endl;
            exit(2);
          }
    }

    void start()
    {
        //开始从网络里读数据
        for(;;)
        {
            char buffer[128];
            struct  sockaddr_in address;
            socklen_t len = sizeof(address);
            ssize_t ret = recvfrom(_socketfd,buffer,sizeof(buffer) ,0,(struct sockaddr*)&address,&len);
        }
    }

    void join();

private:
   // 服务器需要ip和端口号
   std::string _ip;
   uint16_t _port;
   int _socketfd;
};

